package com.magicborrow.activity;

import android.app.Activity;
import android.content.Intent;
import android.location.Location;
import android.os.Bundle;
import android.util.Log;
import android.view.KeyEvent;
import android.view.View;
import android.widget.AdapterView;
import android.widget.EditText;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;

import com.baidu.location.BDLocation;
import com.baidu.location.BDLocationListener;
import com.baidu.location.LocationClient;
import com.baidu.location.LocationClientOption;
import com.baidu.location.Poi;
import com.baidu.mapapi.map.BaiduMap;
import com.baidu.mapapi.map.BitmapDescriptor;
import com.baidu.mapapi.map.BitmapDescriptorFactory;
import com.baidu.mapapi.map.MapStatus;
import com.baidu.mapapi.map.MapStatusUpdateFactory;
import com.baidu.mapapi.map.MapView;
import com.baidu.mapapi.map.MyLocationConfiguration;
import com.baidu.mapapi.map.MyLocationData;
import com.baidu.mapapi.model.LatLng;
import com.baidu.mapapi.search.core.PoiInfo;
import com.baidu.mapapi.search.core.SearchResult;
import com.baidu.mapapi.search.poi.OnGetPoiSearchResultListener;
import com.baidu.mapapi.search.poi.PoiAddrInfo;
import com.baidu.mapapi.search.poi.PoiCitySearchOption;
import com.baidu.mapapi.search.poi.PoiDetailResult;
import com.baidu.mapapi.search.poi.PoiIndoorResult;
import com.baidu.mapapi.search.poi.PoiNearbySearchOption;
import com.baidu.mapapi.search.poi.PoiResult;
import com.baidu.mapapi.search.poi.PoiSearch;
import com.baidu.mapapi.search.poi.PoiSortType;
import com.magicborrow.R;
import com.magicborrow.adapter.AddressAdapter;
import com.magicborrow.beans.AddressBean;
import com.magicborrow.utils.AddressHostUtils;

import java.util.ArrayList;
import java.util.List;

public class AddressActivity extends BaseActivity implements OnGetPoiSearchResultListener {

    private ListView llAddress;
    // 定位相关
    private LocationClient mLocClient;
    public MyLocationListener myListener = new MyLocationListener();
    private MyLocationConfiguration.LocationMode mCurrentMode;
    private BitmapDescriptor mCurrentMarker;
    private AddressAdapter adapter;


    private MapView mMapView;
    private BaiduMap mBaiduMap;
    private boolean isFirstLoc = true;
    private PoiSearch mPoiSearch;
    private ArrayList<AddressBean> datas = new ArrayList<>();
    private ArrayList<AddressBean> oldDatas = new ArrayList<>();
    private BDLocation location;


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_address);
        mPoiSearch = PoiSearch.newInstance();
        mPoiSearch.setOnGetPoiSearchResultListener(this);

        llAddress = (ListView) findViewById(R.id.ll_address);
        adapter = new AddressAdapter(this, datas);
        adapter.setHasIcon(true);
        llAddress.setAdapter(adapter);

        // 地图初始化
        mMapView = (MapView) findViewById(R.id.mv);
        mBaiduMap = mMapView.getMap();
        // 开启定位图层
        mBaiduMap.setMyLocationEnabled(true);
        // 修改为自定义marker
        mCurrentMarker = BitmapDescriptorFactory
                .fromResource(R.mipmap.icon_marker);
        mBaiduMap
                .setMyLocationConfigeration(new MyLocationConfiguration(
                        MyLocationConfiguration.LocationMode.NORMAL, true, mCurrentMarker));

        mLocClient = new LocationClient(this);
        mLocClient.registerLocationListener(myListener);
        LocationClientOption option = new LocationClientOption();
        option.setOpenGps(true); // 打开gps
        option.setCoorType("bd09ll"); // 设置坐标类型
        option.setIsNeedLocationPoiList(true);
        option.setIsNeedAddress(true);//可选，设置是否需要地址信息，默认不需要
        option.setOpenGps(true);//可选，默认false,设置是否使用gps
        option.setLocationNotify(true);//可选，默认false，设置是否当gps有效时按照1S1次频率输出GPS结果
        option.setIsNeedLocationDescribe(true);//可选，默认false，设置是否需要位置语义化结果，可以在BDLocation.getLocationDescribe里得到，结果类似于“在北京天安门附近”
        option.setIsNeedLocationPoiList(true);
        //option.setScanSpan(1000);
        mLocClient.setLocOption(option);


        mLocClient.start();
        getEtSearch().setOnEditorActionListener(new TextView.OnEditorActionListener() {
            @Override
            public boolean onEditorAction(TextView v, int actionId, KeyEvent event) {
                //  showShortMsg("搜索");
                if (location == null) {
                    showShortMsg("无法定位您的当前城市，请稍候再试！");
                }
                mPoiSearch.searchInCity((new PoiCitySearchOption())
                        .city(location.getAddress().city)
                        .keyword(getEtSearch().getText().toString())
                        .pageNum(0).pageCapacity(20));
                if (oldDatas.size() == 0)
                    oldDatas.addAll(datas);
                datas.clear();
                datas.add(oldDatas.get(0));


                return false;
            }
        });
        getEtSearch().setOnFocusChangeListener(new View.OnFocusChangeListener() {
            @Override
            public void onFocusChange(View v, boolean hasFocus) {
                if (hasFocus) {
                    mMapView.setVisibility(View.GONE);
                }
            }
        });
        llAddress.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                ArrayList<AddressBean> beans = AddressHostUtils.getLocalHost(AddressActivity.this);
                if (beans == null) {
                    beans = new ArrayList<AddressBean>();
                }
                beans.add(adapter.getItem(position));
                AddressHostUtils.saveLocalHost(AddressActivity.this, beans);
                finish();

            }
        });
    }

    @Override
    public void onBackPressed() {
        if (oldDatas != null && oldDatas.size() != 0) {
            datas.clear();
            datas.addAll(oldDatas);
            adapter.notifyDataSetChanged();
            oldDatas.clear();
            mMapView.setVisibility(View.VISIBLE);
            getEtSearch().clearFocus();
            return;
        }
        super.onBackPressed();
    }

    private EditText getEtSearch() {
        return (EditText) findViewById(R.id.et_search);
    }

    @Override
    public void onGetPoiResult(PoiResult poiResult) {


        if (poiResult == null || poiResult.error == SearchResult.ERRORNO.RESULT_NOT_FOUND) {
            Log.i("poiinfos", "+" + "出错了");
            return;

        }
        //找到则显示覆盖物
        if (poiResult.error == SearchResult.ERRORNO.NO_ERROR) {


            List<PoiInfo> poiAddrInfos = poiResult.getAllPoi();
            // datas.clear();
            Log.i("poiinfos", "+" + poiAddrInfos);
            if (poiAddrInfos != null)
                for (PoiInfo poiAddrInfo : poiAddrInfos) {
                    AddressBean bean = new AddressBean();
                    bean.setAddress(poiAddrInfo.name);
                    bean.setLat(poiAddrInfo.location.latitude);
                    bean.setLon(poiAddrInfo.location.longitude);
                    bean.setAddressInfo(poiAddrInfo.address);
                    datas.add(bean);
                    Log.i("===", bean.toString());

                }
            adapter.notifyDataSetChanged();
        }
    }

    @Override
    public void onGetPoiDetailResult(PoiDetailResult poiDetailResult) {
        // poiDetailResult.
        if (poiDetailResult.error != SearchResult.ERRORNO.NO_ERROR) {
            Toast.makeText(this, "抱歉，未找到结果", Toast.LENGTH_SHORT)
                    .show();
        } else {
            Toast.makeText(this, poiDetailResult.getName() + ": " + poiDetailResult.getAddress(), Toast.LENGTH_SHORT)
                    .show();
        }
    }

    @Override
    public void onGetPoiIndoorResult(PoiIndoorResult poiIndoorResult) {

    }

    /**
     * 定位SDK监听函数
     */
    public class MyLocationListener implements BDLocationListener {

        @Override
        public void onReceiveLocation(BDLocation location) {
            // map view 销毁后不在处理新接收的位置
            if (location == null || mMapView == null) {
                return;
            }
            AddressActivity.this.location = location;

            MyLocationData locData = new MyLocationData.Builder()
                    .accuracy(location.getRadius())
                    .latitude(location.getLatitude())
                    .longitude(location.getLongitude()).build();
            mBaiduMap.setMyLocationData(locData);
            if (isFirstLoc) {
                isFirstLoc = false;
                LatLng ll = new LatLng(location.getLatitude(),
                        location.getLongitude());
                MapStatus.Builder builder = new MapStatus.Builder();
                builder.target(ll).zoom(18.0f);
                mBaiduMap.animateMapStatus(MapStatusUpdateFactory.newMapStatus(builder.build()));
            }
            AddressBean bean = new AddressBean();
            bean.setAddress("" + ((Poi) location.getPoiList().get(0)).getName());
            bean.setLat(location.getLatitude());
            bean.setLon(location.getLongitude());
            bean.setAddressInfo("" + location.getAddrStr());
            datas.clear();
            datas.add(bean);

            searchNeayBy("写字楼", location.getLatitude(), location.getLongitude());
            searchNeayBy("小区", location.getLatitude(), location.getLongitude());


            //==========================


        }

        public void onReceivePoi(BDLocation poiLocation) {

        }
    }


    /**
     * 搜索周边地理位置
     */
    private void searchNeayBy(String keword, double mCurrentLantitude, double mCurrentLongitude) {
        PoiNearbySearchOption option = new PoiNearbySearchOption();
        option.keyword(keword);
        option.sortType(PoiSortType.distance_from_near_to_far);
        option.location(new LatLng(mCurrentLantitude, mCurrentLongitude));
        option.radius(1000);
        option.pageNum(0);
        option.pageCapacity(4);
        mPoiSearch.searchNearby(option);


    }

    @Override
    protected void onPause() {
        super.onPause();
        if(mMapView == null){
            return;
        }
        mMapView.onPause();
    }

    @Override
    protected void onResume() {
        super.onResume();
        if(mMapView == null){
            return;
        }
        mMapView.onResume();
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();

        if(mLocClient != null){
        // 退出时销毁定位
            mLocClient.stop();
        }
        if(mBaiduMap != null) {
            // 关闭定位图层
            mBaiduMap.setMyLocationEnabled(false);
        }
        if(mMapView != null){
            return;
        }
        mMapView.onDestroy();
        mMapView = null;
    }
}
